<template>
  <div>
    <h3>发表评论</h3>
    <van-notice-bar left-icon="volume-o" scrollable text="谨慎评论，不当嘴炮!!!" />
    <van-divider />
    <div>
      <!-- 文本域 -->
      <textarea id="commentId" cols="30" rows="10" v-model="textValue" placeholder="请输入留言"></textarea>
      <!-- 发表评论按钮 -->
      <van-button class="submitComment" type="primary" text="发表评论" @click="addComment" />

      <!-- 评论列表 -->
      <van-list finished-text="没有更多了">
        <div v-for="(item,index) in commentList" :key="index">
          <!-- 评论头部 -->
          <div class="title">
            <span>第{{commentList.length-index}}楼</span>
            <span>用户: {{item.user_name}}</span>
            <span>发表时间: {{item.add_time.substr(0,10)}}</span>
          </div>
          <!-- 评论内容 -->
          <div class="content">{{item.content}}</div>
        </div>
      </van-list>
      <!-- 加载更多按钮 -->
      <van-button color="red" plain text="加载更多" @click="showMore" style="width: 100%" />
    </div>
  </div>
</template>

<script>
import { mapState } from 'vuex'
export default {
  data () {
    return {
      commentList: [],
      //   文本域内容
      textValue: '',
      pageindex: 1
    }
  },
  mounted () {
    // 得到对应文章的已有的评论数据
    this.getComment()
    // console.log("评论页面获得id", this.artId);
  },
  methods: {
    async getComment () {
      const { data: res } = await this.$http.get(
        `/api/getcomments/${this.artId}?pageindex=${this.pageindex}`
      )
      this.commentList = res.message
    },
    // 发表评论
    async addComment () {
      // 如果文本域为空
      if (this.textValue.trim() === '') {
        this.$toast('请输入有效评论内容！')
        this.textValue = ''
        return
      }
      const { data: res } = await this.$http.post(
        `/api/postcomment/${this.artId}`,
        {
          content: this.textValue.trim()
        }
      )
      console.log(res)
      this.$toast('你已发言完毕!')
      this.textValue = ''
      this.getComment()
    },
    // 加载更多评论
    async showMore () {
      const { data: res } = await this.$http.get(
        `/api/getcomments/${this.artId}?pageindex=${this.pageindex + 1}`
      )
      this.commentList = res.message
    }
  },
  computed: {
    //   获取当前文章id
    ...mapState(['artId'])
  }
}
</script>

<style lang="less" scoped>
h3 {
  margin-bottom: 0px;
}
#commentId {
  box-sizing: border-box;
  width: 100%;
  height: 100px;
  border: 1px solid #036;
  padding: 10px;
  /*防止用户拖拽文本域*/
  resize: none;
  font-size: 14px;
}
.vanCell {
  padding: 0;
}
.submitComment {
  width: 100%;
}
.title {
  margin-top: 5px;
  background-color: #ccc;
  span {
    margin-left: 8px;
  }
}
.content {
  line-height: 35px;
  text-indent: 2em;
  font-size: 12px;
}
</style>
